package com.wfbi.security.chapter15;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.firewall.HttpFirewall;
import org.springframework.security.web.firewall.StrictHttpFirewall;
import org.springframework.session.FindByIndexNameSessionRepository;
import org.springframework.session.security.SpringSessionBackedSessionRegistry;

/**
 * @author wfbi
 * @version 1.0
 * @date 2021/12/27 2:13 PM
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    FindByIndexNameSessionRepository sessionRepository;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest()
                .authenticated()
                .and()
                .formLogin()
                .permitAll()
                .and()
                .csrf()
                .disable()
                .sessionManagement()
                // 一个用户只能有一个终端登录
                .maximumSessions(1)
                // 多余终端登录被阻止
                .maxSessionsPreventsLogin(true)
                // 设置会话注册表
                .sessionRegistry(sessionRegistry());
    }

    /**
     * 使用spring session提供的sessionRegistry来维护会话注册表
     *
     * @param null:
     * @author: wfbi
     * @date: 2021/12/31 11:12 AM
     * @return: null
     **/
    @Bean
    SpringSessionBackedSessionRegistry sessionRegistry() {
        return new SpringSessionBackedSessionRegistry(sessionRepository);
    }
}
